import {
	apiUrl,
	ymdApiUrl
} from '../config'
import {
	token,
	userInfo
} from '../utils/token'
import {
	formatGetUri
} from '../utils/util.js'


const request = {}


request.globalRequest = (url, method, params, showLoading = true) => {
	const headers = {
		'Content-Type': 'application/json'
	}
	headers["X-Access-Token"] = token.get() ? token.get() : ''
	if (showLoading) {
		uni.showLoading({
			title: '加载中'
		});
	}
	const body = params.data ? params.data : {};
	let requestUrl = '';
	if(url.includes('ymd')){
		requestUrl = ymdApiUrl + url + formatGetUri(params.params)
	}else{
		requestUrl = apiUrl + url + formatGetUri(params.params)
	}
	
	return uni.request({
		url: requestUrl,
		method,
		data: body,
		dataType: 'json',
		header: headers
	}).then(res => {
		if (showLoading) {
			uni.hideLoading();
		}
		console.log(res)
		if (res) {
			const {
				statusCode,
				data
			} = res
			if (statusCode == 200) {
				if (data.code == -2) {
					token.clear();
					userInfo.clear()
				}
				return data
			} else if (statusCode == 401) {
				token.clear();
				userInfo.clear()
				throw data
			} else {
				throw data
			}
		} else {
			uni.showToast({
				title: "请求的接口没有响应",
				icon: 'none'
			})
			throw data
		}

	}).catch(err => {
		
		if (showLoading) {
			uni.hideLoading();
		}
		
		console.log(err)
		if (err.status == 500 || err.status == 401) {
			token.clear();
			userInfo.clear()
		} else {
			uni.showToast({
				title: err.message,
				icon: 'none'
			})
		}
		throw err
	})


}


export default request
